package openase.audio;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// TODO rewrite with better use of memory and with better performance
public class MemoryStorage extends Storage {

	private final Map<Integer, AudioInfo> audios = new HashMap<Integer, AudioInfo>();
	private final Map<Integer, List<AudioFingerprint>> fingerprints = new HashMap<Integer, List<AudioFingerprint>>();

	@Override
	public void addAudio(AudioInfo audio) throws StorageException {
		synchronized (audios) {
			int newId = audios.size();
			audio.setId(newId);
			audios.put(newId, audio);
		}
	}

	@Override
	public void addFingerprint(AudioFingerprint fingerprint) throws StorageException {
		List<AudioFingerprint> list = fingerprints.get(fingerprint.getSource().getId());
		if (list == null) {
			list = new ArrayList<AudioFingerprint>(1);
			fingerprints.put(fingerprint.getSource().getId(), list);
		}
		list.add(fingerprint);
	}

	@Override
	public AudioInfo getAudio(int id) throws StorageException {
		return audios.get(id);
	}

	@Override
	public AudioInfo getAudio(String name) throws StorageException {
		for (AudioInfo audio : audios.values()) {
			if (name.equals(audio.getInfo())) {
				return audio;
			}
		}
		return null;
	}

	@Override
	public int getAudioCount() throws StorageException {
		return audios.size();
	}

	@Override
	public int getFingerprintCount() throws StorageException {
		int count = 0;
		for (List<AudioFingerprint> list : fingerprints.values()) {
			count += list.size();
		}
		return count;
	}

	@Override
	public int getFingerprintCount(AudioInfo audio) throws StorageException {
		List<AudioFingerprint> list = fingerprints.get(audio.getId());
		if (list == null) {
			return 0;
		}
		return list.size();
	}

	@Override
	public AudioFingerprint[] getMatchingFingerprints(long hash) throws StorageException {
		// FIXME Auto-generated method stub
		return null;
	}

}
